package com.qd.pandaparkflow.compment.park;

import cn.hutool.core.math.Money;
import com.qd.common.panda.domain.entity.rule.Rule2DTO;
import com.qd.pandaparkflow.context.PriceContext;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * 起步价,比如：前两个小时五块，以后每小时3元
 *
 * @author sjk
 */
@ConditionalOnProperty(prefix = "liteflow", name = "enable", havingValue = "true")
@LiteflowComponent(value = "startPriceCmp")
@Slf4j
public class StartPriceComponent extends NodeComponent {

    @Override
    public void process() throws Exception {
        //剩余时间
        long timeLeft;
        final PriceContext priceContext = this.getContextBean(PriceContext.class);
        Money allPriceBigDecimal = new Money(Optional.ofNullable(priceContext.getFinalOrderPrice()).orElse(new BigDecimal(0L)));
        Money finalOrderPriceBigDecimal = new Money(0L);

        final Long minutes = priceContext.getMinutes();
        Rule2DTO rule = (Rule2DTO) priceContext.getRules().get(0);

        //把前两个小时转换成120分钟
        final long minute = (rule.getStartHour() * 60);
        //前两个小时的价格
        final Money startPrice = new Money(rule.getStartPrice());
        //后面每个小时的价格
        final Money hourPrice = new Money(rule.getPrice());
        StringBuilder log = new StringBuilder("按起步价计算,规定小时[").append(rule.getStartHour()).append("]").append(",单价[").append(startPrice).append("]")
                .append(",实际分钟数[").append(minutes).append("]");
        if (minutes >= minute) {
            timeLeft = minutes - minute;
            finalOrderPriceBigDecimal = finalOrderPriceBigDecimal.add(startPrice);
            priceContext.setFinalOrderPrice(allPriceBigDecimal.add(finalOrderPriceBigDecimal).getAmount());
        } else {
            timeLeft = minutes;
        }
        priceContext.setHasNextStep(timeLeft > 0);
        priceContext.setMinutes(timeLeft);
        priceContext.setUnitPrice(hourPrice.getAmount());
        log.append(",当前金额[").append(finalOrderPriceBigDecimal).append("]").append(",总金额[").append(priceContext.getFinalOrderPrice().toPlainString()).append("},剩余计算时间[").append(timeLeft).append("]");
        priceContext.getPrintLog().add(log.toString());
    }
}